//
//  NewHomeViewController.m
//  GC_OC
//
//  Created by  Quan He on 2022/4/8.
//


#import "LearningHistoryViewController.h"
#import "CalendarManager.h"
#import "LearningHistoryService.h"
#import "CurriculumModel.h"
#import "NewHomeInfoCell.h"
#import "LearningHistoryService.h"
#import "NewHomeInfoHeaderView.h"
#import "NewHomeInfoFooterView.h"

@interface LearningHistoryViewController ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, CalendarEventSource>
@property (nonatomic,strong) CalendarManager *calendarManager;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *titleArr;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL needRefresh;
@property (nonatomic, strong) NSMutableSet *hideSectionSet;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIButton *showButton;
@property (nonatomic, strong) UILabel *timeLabel;


@end

@implementation LearningHistoryViewController

#pragma mark - Life
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"学习历史";
    [self initData];
    [self setupUI];
    [self requestData];
    
    [self.calendarManager showSingleWeek];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}


#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.calendarManager.weekDayView];
    [self.view addSubview:self.calendarManager.calenderScrollView];
    
    [CalendarAppearance share].calendarBgColor = self.view.backgroundColor;
    //周视图背景颜色
    [CalendarAppearance share].weekDayBgColor = self.view.backgroundColor;
    [CalendarAppearance share].scrollBgcolor = self.view.backgroundColor;
    [CalendarAppearance share].weekDayTextColor = [UIColor grayColor];
    [CalendarAppearance share].weekDayTextFont = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
    
    [CalendarAppearance share].dayCircleColorSelected = [UIColor colorWithRed:0.29 green:0.36 blue:0.95 alpha:1.00];
    [CalendarAppearance share].dayCircleColorToday = [UIColor colorWithRed:0.29 green:0.36 blue:0.95 alpha:1.00];
    [CalendarAppearance share].dayBorderColorToday = [UIColor colorWithRed:0.29 green:0.36 blue:0.95 alpha:1.00];
    [CalendarAppearance share].dayDotColor = [UIColor colorWithRed:0.29 green:0.36 blue:0.95 alpha:1.00];
    [CalendarAppearance share].dayDotColorSelected = [UIColor colorWithRed:0.29 green:0.36 blue:0.95 alpha:1.00];
    [CalendarAppearance share].isShowLunarCalender = NO;
    [CalendarAppearance share].dayTextColorOtherMonth = [UIColor lightGrayColor];
    [CalendarAppearance share].lunarDayTextColorOtherMonth = [UIColor lightGrayColor];
    [CalendarAppearance share].dayCircleSize = 40;
    
    self.calendarManager.calenderScrollView.bgColor = self.view.backgroundColor;
    self.calendarManager.eventSource = self;

    [self.calendarManager reloadAppearanceAndData];
    
    [self.view addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.calendarManager.calenderScrollView.tableView.mas_top);
        make.height.equalTo(@(30));
    }];

    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(self.topView.mas_bottom);
    }];
    
    
    //删除按钮
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 25)];
    button.hitTestEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10);
    button.adjustsImageWhenHighlighted = NO;
    [button addTarget:self action:@selector(deleteAllInfo) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    
    UIView *itemView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 25, 25)];
    [itemView addSubview:button];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:itemView];
    
    self.navigationItem.rightBarButtonItem = backItem;
}

#pragma mark - Business
- (void)initData {
    self.hideSectionSet = [NSMutableSet set];
}
#pragma mark - Function


#pragma mark - Action
- (void)showCalendar:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    [self showAllCalendarView:sender.selected];
}

- (void)showAllCalendarView:(BOOL)showAll {
    if (showAll) {
        [self.calendarManager showAllWeek];
    }else {
        [self.calendarManager showSingleWeek];
    }
    self.timeLabel.hidden = !showAll;
    __weak typeof(self) weakSelf = self;

    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.calendarManager.weekDayView.frame = CGRectMake(0, showAll ? 30 : 0, weakSelf.view.frame.size.width, 30);
        weakSelf.calendarManager.calenderScrollView.frame = CGRectMake(0, CGRectGetMaxY(weakSelf.calendarManager.weekDayView.frame), CGRectGetWidth(weakSelf.view.frame), CGRectGetHeight(weakSelf.view.frame)-CGRectGetMaxY(weakSelf.calendarManager.weekDayView.frame));
    }];
}

- (void)deleteAllInfo {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否删除所有学习历史？" preferredStyle:(UIAlertControllerStyleAlert)];
    
    __weak typeof(self) weakSelf = self;

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[LearningHistoryService sharedInstance] clearAllInfo];
        [weakSelf requestData];
    }];
    
    [alertVC addAction:confirmAction];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {

    }];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

- (void)hideInfoWithSection:(NSInteger)section isHide:(BOOL)isHide{
    
    if (isHide) {
        [self.hideSectionSet addObject:self.titleArr[section]];
    }else {
        [self.hideSectionSet removeObject:self.titleArr[section]];
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - Request
- (void)requestData {
    NSMutableArray *data = [[LearningHistoryService sharedInstance] getLearningHistoryInfo];
    NSMutableArray *dataArr = [NSMutableArray array];
    NSMutableArray *titleArr = [NSMutableArray array];

    for (NSDictionary *dic in data) {
        NSArray *array = [NSMutableArray arrayWithArray:dic[@"content"]];
        NSMutableArray *modelArr = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            CurriculumModel *model = [[CurriculumModel alloc] initWithDic:dic];
            [modelArr addObject:model];
        }
        [dataArr addObject:modelArr];
        NSString *time = dic[@"time"];
        [titleArr addObject:[LearningHistoryService timeTrainsform:time]];
    }
    self.dataArr = dataArr;
    self.titleArr = titleArr;
    [self.tableView reloadData];
    [self.calendarManager reloadAppearanceAndData];

}

#pragma mark - CalendarEventSource
- (BOOL)calendarHaveEventWithDate:(NSDate *)date {
    NSDateFormatter  *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-M-dd"];
    NSString * time = [dateformatter stringFromDate:date];
    if ([self.titleArr containsObject:time]) {
        return YES;
    }
    return NO;
}

- (void)calendarDidSelectedDate:(NSDate *)date {
    if (self.titleArr.count != 0) {
        NSDateFormatter  *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-M-dd"];
        NSString * time = [dateformatter stringFromDate:date];
        if ([self.titleArr containsObject:time]){
            [self.calendarManager showSingleWeek];

            self.showButton.selected = NO;

            NSInteger section = [self.titleArr indexOfObject:time];
            
            //展开
            [self showSection:section];
        }
    }
    [self calendarDidLoadPageCurrentDate:date];
}

- (void)calendarDidLoadPageCurrentDate:(NSDate *)date {
    NSDateFormatter  *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY年M月"];
    NSString * time = [dateformatter stringFromDate:date];
    self.timeLabel.text = time;
}

- (void)showSection:(NSInteger)section {
    [self hideInfoWithSection:section isHide:NO];
    
    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];

    [self.tableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *infoList = self.dataArr[section];
    return infoList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.titleArr[indexPath.section];
    BOOL hide = [self.hideSectionSet containsObject:title];
    return hide ? 0 : 92;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 38;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    NewHomeInfoFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([NewHomeInfoFooterView class])];
    if (!footer) {
        footer = [[NewHomeInfoFooterView alloc]initWithReuseIdentifier:NSStringFromClass([NewHomeInfoFooterView class])];
    }
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 62;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NewHomeInfoHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([NewHomeInfoHeaderView class])];
    
    if (!header) {
        header = [[NewHomeInfoHeaderView alloc]initWithReuseIdentifier:NSStringFromClass([NewHomeInfoHeaderView class])];
    }
    NSString *title = self.titleArr[section];
    header.titleLabel.text = title;
    header.hide = [self.hideSectionSet containsObject:title];

    __weak typeof(self) weakSelf = self;
    header.hideAction = ^(BOOL isHide) {
        [weakSelf hideInfoWithSection:section isHide:isHide];
    };
    return header;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewHomeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewHomeInfoCell"];
    if (!cell) {
        cell = [[NewHomeInfoCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"NewHomeInfoCell"];
    }
    CurriculumModel *model = self.dataArr[indexPath.section][indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *array = self.dataArr[indexPath.section];
    CurriculumModel *cellModel = array[indexPath.row];
    [[PlayModel sharedModel] play:cellModel listArr:array viewPlayY:SCREEN_HEIGHT -  50 - HY_BottomWhiteBar_Height];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //在这里实现删除操作
    NSMutableArray *array = self.dataArr[indexPath.section];
    CurriculumModel *cellModel = array[indexPath.row];
    [[LearningHistoryService sharedInstance] removeInfo:[cellModel dictionary]];
    
    [self requestData];

}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
}

// 修改Delete按钮文字为“删除”
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


#pragma mark DZNEmptyDataSetDelegate & DZNEmptyDataSetSource
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
    NSString *text = @"暂无内容浏览历史";
    NSDictionary *attributes = @{
                                 NSFontAttributeName: [UIFont systemFontOfSize:15 weight:UIFontWeightRegular],
                                 NSForegroundColorAttributeName: [UIColor grayColor]};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

#pragma mark - LazyLoad
- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = self.view.backgroundColor;
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:1.00];
        [_topView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.centerY.equalTo(_topView);
            make.height.equalTo(@(0.5));
        }];
        
        [_topView addSubview:self.showButton];
        [self.showButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_topView);
            make.height.width.equalTo(@(20));
            make.right.equalTo(_topView.mas_right).offset(-40);
        }];
    }
    return _topView;
}

- (UIButton *)showButton {
    if (!_showButton) {
        _showButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_showButton setBackgroundImage:[UIImage imageNamed:@"xiala-yuan"] forState:UIControlStateNormal];
        [_showButton setBackgroundImage:[UIImage imageNamed:@"shangla-yuan"] forState:UIControlStateSelected];
        [_showButton setBackgroundImage:[UIImage imageNamed:@"shangla-yuan"] forState:UIControlStateSelected | UIControlStateHighlighted];
        [_showButton addTarget:self action:@selector(showCalendar:) forControlEvents:UIControlEventTouchUpInside];
        _showButton.hitTestEdgeInsets = UIEdgeInsetsMake(-5, -5, -5, -5);
        [_showButton setBackgroundColor:self.view.backgroundColor];
        _showButton.adjustsImageWhenHighlighted = NO;
    }
    return _showButton;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - topHeight) style:UITableViewStyleGrouped];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        UINib *lib = [UINib nibWithNibName:@"NewHomeInfoCell" bundle:nil];
        [_tableView registerNib:lib forCellReuseIdentifier:@"NewHomeInfoCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = self.view.backgroundColor;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, 60)];
    }
    return _tableView;
}

- (CalendarManager *)calendarManager {
    if (!_calendarManager) {
        _calendarManager = [CalendarManager new];
        _calendarManager.eventSource = self;
        _calendarManager.weekDayView = [[CalendarWeekDayView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        
        _calendarManager.calenderScrollView = [[CalendarScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_calendarManager.weekDayView.frame), CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-CGRectGetMaxY(_calendarManager.weekDayView.frame))];
    }
    return _calendarManager;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        _timeLabel.textColor = [UIColor blackColor];
        _timeLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
        _timeLabel.hidden = YES;
        _timeLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _timeLabel;
}
@end
